﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ArtMath.Window
{
    public partial class WindowsManagerWindow : Form
    {
        public WindowsManagerWindow(Dictionary<ToolStripMenuItem, DocumentWindow> wins)
        {
            InitializeComponent();
            foreach (KeyValuePair<ToolStripMenuItem, DocumentWindow> pair in wins)
            {
                ListViewItem item = new ListViewItem(pair.Key.Text)
                {
                    Tag = pair.Value.LinkedDocument,
                };
                item.SubItems.Add(pair.Value.LinkedDocument.LinkedFile == null ? string.Empty : pair.Value.LinkedDocument.LinkedFile.Name);
                lvWindows.Items.Add(item);
            }
        }

        private void lvWindows_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnActivate.Enabled = lvWindows.SelectedItems.Count == 1;
            btnSave.Enabled = btnCloseWindow.Enabled = lvWindows.SelectedItems.Count > 0;
        }

        private void btnActivate_Click(object sender, EventArgs e)
        {
            if (lvWindows.SelectedItems.Count == 1)
            {
                Document doc = lvWindows.SelectedItems[0].Tag as Document;
                doc.Activate();
                DialogResult = DialogResult.OK;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Program.WinDocuments.Save(lvWindows.SelectedItems.OfType<ListViewItem>().Select((ListViewItem item) => { return item.Tag as Document; }));
        }

        private void btnCloseWindow_Click(object sender, EventArgs e)
        {
            Document[] closed;
            try
            {
                closed = Program.WinDocuments.CloseDocument(lvWindows.SelectedItems.OfType<ListViewItem>().Select((ListViewItem item) => { return item.Tag as Document; }));
            }
            catch (OperationCanceledException ex)
            {
                closed = ex.Data["Closed"] as Document[];
            }
            foreach (ListViewItem item in lvWindows.SelectedItems)
            {
                if (Array.IndexOf(closed, item.Tag) >= 0)
                {
                    item.Remove();
                }
            }
        }
    }
}
